﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Xml;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using NetworkUtils;


namespace Client
{
    public class ServerClient
    {
        private TcpClient client;
        private NetworkStream streamToServer;
        private const int BufferSize = 1024 * 8;
        private byte[] buffer;
        private string msg = "";

        public ServerClient()
        {
            try
            {
                client = new TcpClient();
                client.Connect("127.0.0.1", 8500);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            buffer = new byte[BufferSize];
            Console.WriteLine("Server Connected！{0} --> {1}",
            client.Client.LocalEndPoint, client.Client.RemoteEndPoint);
            streamToServer = client.GetStream();
        }

        public void TestSendMsg()
        {
            //string msg = "我来看看你能不能收到";
            Data d = new Data("600006", 12.3f);
            msg = Serialize(d);
            Console.WriteLine("序列化后字符：" + msg);
            ProtocolObj ptcObj = new ProtocolObj(msg.Length, MsgType.Data);
            string ptcStr = ProtocolHelper.ToString(ptcObj);
            SendMsg(ptcStr + msg);
        }

        public string Serialize(Object obj)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            byte[] buffer = ms.GetBuffer();
            ms.Close();
            string objStr = Encoding.Unicode.GetString(buffer, 0, buffer.Length);
            return objStr;
        }


        public void SendMsg(string msg)
        {
            byte[] temp = Encoding.Unicode.GetBytes(msg);
            try
            {
                lock (streamToServer)
                {
                    streamToServer.Write(temp, 0, temp.Length);
                    streamToServer.Flush();
                }
                Console.WriteLine("Sent: {0}", msg);
            }
            catch(Exception ex)
            {
                //在这触发一个断线事件
                Console.WriteLine(ex.Message);
                return;
            }
        }
    }
}
